<?php
/**
 * Created by Administrator
 * User: longli
 * VX: isa1589518286
 * Date: 2020/08/12
 * Time: 10:49
 * @link http://www.lmterp.cn
 */

namespace app\common\service\platform;


use app\common\library\Tools;
use app\common\model\AccountSyncLog;
use app\common\model\Orders;
use app\common\model\OrdersTemp;
use app\common\service\orders\OrderService;
use Exception;
use GuzzleHttp\Client;
use think\facade\Log;

/**
 * eprice 接口服务 开发文档需要登录才能看到
 * Class EpriceService
 * @package app\common\service\eprice
 * @link https://marketplace.eprice.it/help/topics/home_pages/seller_connectors_api.htm
 */
class EpriceService extends BasePlatformService
{
    public static $tokenField = [
        'required' => [ // 必填字段
            [
                'type' => 'text',
                'name' => 'secret_key',
                'field' => 'secret_key',
            ],
        ],
        'option' => [ // 可选字段
        ],
    ];

    /**
     * HTTP 客户端
     * @var Client
     */
    protected $client;

    public function init()
    {
        $this->client = new Client(['base_uri' => $this->getBaseUrl(), 'timeout' => 10]);
        $this->offsetDate = date('Z');
    }

    /**
     * 获取订单列表
     * @param array $params 参数配置，默认抓取当天订单
     * <ul>
     * <li>string start_date 要抓取的时间，默认为今天</li>
     * <li>string status 订单状态，默认 SHIPPING</li>
     * </ul>
     * @param bool $replace 是否替换原有的订单，默认不替换
     * @return array|bool
     * @date 2020/08/13
     * @author longli
     * @link https://marketplace.eprice.it/api/orders
     */
    public function getOrderList($params = [], $replace = false)
    {
        Log::info(sprintf("Eprice 批量同步账号【%d】订单，请求参数:【%s】", $this->getAccountId(), json_encode($params)));
        $startSyncTime = time();
        $args = [
            "start_date" => !empty($params['start_date']) ? $this->formatTimeToDate($params['start_date']) : $this->formatTimeToDate(date('Y-m-d')),
            "end_date" => $this->formatTimeToDate(),
            "order_state_codes" => !empty($params['status']) ? $params['status'] : "SHIPPING", //WAITING_ACCEPTANCE
            "paginate" => "false",
        ];
        $url = $this->getBaseUrl() . '/api/orders';
        $response = Tools::curlGet($url, $args, $this->getHeader());
        if(!$response['status'] || !Tools::isJson($response['data'], $orders))
        {
            Log::info(sprintf("Eprice 同步订单接口异常, 账号:【%d】, 参数:【%s】", $this->getAccountId(), json_encode($response['info'])));
            return false;
        }
        if(empty($orders['orders'])) return false; // 无订单数据
        foreach($orders['orders'] as $order)
        {
            $this->pushOrderToTemp($order['commercial_id'], $order, $replace);
        }
        // 添加同步订单日志
        AccountSyncLog::addLog($this->getAccountId(), $startSyncTime, time(), $args);
    }

    /**
     * 获取请求头信息
     * @date 2020/08/13
     * @author longli
     * @return string[]
     */
    public function getHeader()
    {
        $account = $this->getAccount();
        return [
            "Content-type:application/json;",
            "Accept:application/json",
            "Authorization:{$account->token->secret_key}"
        ];
    }

    public function syncOrder(OrdersTemp $ordersTemp)
    {
        $data = $ordersTemp->order_info;
        $info = [];
        foreach($data['order_lines'] as $item)
        {
            $info[] = [
                "item_id"       => $item['offer_id'], // 商品 id
                "qty"           => $item['quantity'], // 数量
                "return_qty"    => 0, // 取消数量
                "price"         => $item['price'], // 售价
                "platform_sku"  => $item['offer_sku'], // sku
                "name"          => $item['product_title'], // 产品名称
                "image_url"         => "https://marketplace.eprice.it/mmp" . $item["product_medias"][2]["media_url"], // 图片地址
            ];
        }
        $platform = $this->getAccountById($ordersTemp->account_id)->platform;
        $address = & $data['customer']['shipping_address'];
        $order = [
            "order_no"                  => $ordersTemp->order_no,
            "account_id"                => $ordersTemp->account_id,
            "platform_name"             => $platform->name, // 平台名称
            "order_platform_status"     => $data["order_state"], // 订单在平台的状态
            "buyer_first_name"          => $address['firstname'], // 客户名称
            "buyer_last_name"           => $address['lastname'], // 客户名称
            "buyer_phone"               => $address["phone_secondary"], // 电话
            "buyer_country_code"        => $address['country_iso_code'], // 国家编码
            "buyer_city"                => $address['city'], // 城市
            "buyer_province"            => $address['state'], // 省，州
            "buyer_post_code"           => $address['zip_code'], // 邮编
            "buyer_address_1"           => $address['street_1'], // 买家收货地址1
            "buyer_address_2"           => $address['street_2'], // 买家收货地址2
            "shipping_price"            => '0.00', // 订单运费
            "order_source_create_time"  => $this->parseTimeToDate($data['created_date'], $this->offsetDate), // 订单在平台生成的时间
            "latest_delivery_time"      => $this->parseTimeToDate("{$data['leadtime_to_ship']}day", $this->offsetDate), // 最迟发货时间
            "order_price"               => $data['price'], // 订单金额
            "total_price"               => $data['total_price'], // 订单总金额
            "order_pay_time"            => $this->parseTimeToDate($data['customer_debited_date'], $this->offsetDate), // 订单支付时间
            "currency"                  => $data['currency_iso_code'], // 币种
            "platform_remark"           => "", // 买家备注信息
            "order_detail" => $info,
        ];
        return OrderService::getInstance()->addOrder($order);
    }

    public function markDelivery($orderIds = [])
    {
        foreach($this->getNeedMarkOrders($orderIds) as $order)
        {
            try
            {
                if($response = $this->client->put("/api/orders/{$order->order_no}/tracking", [
                    "body" => json_encode([
                        "carrier_code" => $order->logistics_name,
                        "carrier_name" => 'Other',
                        "carrier_url" => "http://www.yuntrack.com/",
                        "tracking_number" => $order->track_num
                    ]),
                    "headers" => $this->getHeader(),
                ])->getBody()->getContents())
                {
                    Log::info(sprintf("Eprice 订单号【%s】, 上传运单异常：【%s】, 错误信息：【%s】", $order->order_no, $order->track_num, $response));
                    continue;
                }
                // 验证是否上传成功
                if($response = $this->client->put("/api/orders/{$order->order_no}/ship", [
                    "body" => json_encode([
                        'shop_id' => [$this->getAccount()->token->shop_id]
                    ]),
                    "headers" => $this->getHeader(),
                ])->getBody()->getContents())
                {
                    Log::info(sprintf("Eprice 订单号【%s】, 验证运单异常：【%s】, 错误信息：【%s】", $order->order_no, $order->track_num, $response));
                }
                else
                {
                    $order->is_flag_sent = Orders::FLAG_SENT_YES;
                    $order->sent_time = Tools::now();
                    $order->save();
                }
            }catch (Exception $e)
            {
                Log::info(sprintf("Worten tracking 订单号【%s】, 上传运单异常：【%s】, 错误信息：【%s】", $order->order_no, $order->track_num, $e->getMessage()));
            }
        }
    }
}